using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using ObjectLib;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ObjectParser
{
	/// <summary>
	/// Summary description for DbSourceDialog.
	/// </summary>
	public class DbSourceDialog : System.Windows.Forms.Form
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}
		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.label1 = new System.Windows.Forms.Label();
			this.label2 = new System.Windows.Forms.Label();
			this.label3 = new System.Windows.Forms.Label();
			this.label4 = new System.Windows.Forms.Label();
			this.label5 = new System.Windows.Forms.Label();
			this.label6 = new System.Windows.Forms.Label();
			this.textDriver = new System.Windows.Forms.TextBox();
			this.textDbName = new System.Windows.Forms.TextBox();
			this.textServerName = new System.Windows.Forms.TextBox();
			this.textUsername = new System.Windows.Forms.TextBox();
			this.textPassword = new System.Windows.Forms.TextBox();
			this.textOption = new System.Windows.Forms.TextBox();
			this.rtbLog = new System.Windows.Forms.RichTextBox();
			this.butOk = new System.Windows.Forms.Button();
			this.label7 = new System.Windows.Forms.Label();
			this.cmDbEdit = new System.Windows.Forms.ContextMenu();
			this.mAddNew = new System.Windows.Forms.MenuItem();
			this.mDelete = new System.Windows.Forms.MenuItem();
			this.comboDatabases = new System.Windows.Forms.ComboBox();
			this.mEdit = new System.Windows.Forms.MenuItem();
			this.SuspendLayout();
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(8, 56);
			this.label1.Name = "label1";
			this.label1.TabIndex = 0;
			this.label1.Text = "Driver";
			this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(8, 80);
			this.label2.Name = "label2";
			this.label2.TabIndex = 1;
			this.label2.Text = "Database Name";
			this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(8, 104);
			this.label3.Name = "label3";
			this.label3.TabIndex = 2;
			this.label3.Text = "Server";
			this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
			// 
			// label4
			// 
			this.label4.Location = new System.Drawing.Point(8, 152);
			this.label4.Name = "label4";
			this.label4.TabIndex = 3;
			this.label4.Text = "User";
			this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
			// 
			// label5
			// 
			this.label5.Location = new System.Drawing.Point(8, 176);
			this.label5.Name = "label5";
			this.label5.TabIndex = 4;
			this.label5.Text = "Password";
			this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
			// 
			// label6
			// 
			this.label6.Location = new System.Drawing.Point(8, 128);
			this.label6.Name = "label6";
			this.label6.TabIndex = 5;
			this.label6.Text = "Option";
			this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
			// 
			// textDriver
			// 
			this.textDriver.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.textDriver.Location = new System.Drawing.Point(112, 56);
			this.textDriver.Name = "textDriver";
			this.textDriver.Size = new System.Drawing.Size(224, 20);
			this.textDriver.TabIndex = 6;
			this.textDriver.Text = "";
			// 
			// textDbName
			// 
			this.textDbName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.textDbName.Location = new System.Drawing.Point(112, 80);
			this.textDbName.Name = "textDbName";
			this.textDbName.Size = new System.Drawing.Size(224, 20);
			this.textDbName.TabIndex = 7;
			this.textDbName.Text = "";
			// 
			// textServerName
			// 
			this.textServerName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.textServerName.Location = new System.Drawing.Point(112, 104);
			this.textServerName.Name = "textServerName";
			this.textServerName.Size = new System.Drawing.Size(224, 20);
			this.textServerName.TabIndex = 8;
			this.textServerName.Text = "";
			// 
			// textUsername
			// 
			this.textUsername.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.textUsername.Location = new System.Drawing.Point(112, 152);
			this.textUsername.Name = "textUsername";
			this.textUsername.Size = new System.Drawing.Size(224, 20);
			this.textUsername.TabIndex = 9;
			this.textUsername.Text = "";
			// 
			// textPassword
			// 
			this.textPassword.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.textPassword.Location = new System.Drawing.Point(112, 176);
			this.textPassword.Name = "textPassword";
			this.textPassword.PasswordChar = '*';
			this.textPassword.Size = new System.Drawing.Size(228, 20);
			this.textPassword.TabIndex = 10;
			this.textPassword.Text = "";
			// 
			// textOption
			// 
			this.textOption.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.textOption.Location = new System.Drawing.Point(112, 128);
			this.textOption.Name = "textOption";
			this.textOption.Size = new System.Drawing.Size(224, 20);
			this.textOption.TabIndex = 11;
			this.textOption.Text = "";
			// 
			// rtbLog
			// 
			this.rtbLog.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
				| System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.rtbLog.Location = new System.Drawing.Point(8, 240);
			this.rtbLog.Name = "rtbLog";
			this.rtbLog.ReadOnly = true;
			this.rtbLog.Size = new System.Drawing.Size(328, 160);
			this.rtbLog.TabIndex = 13;
			this.rtbLog.Text = "";
			// 
			// butOk
			// 
			this.butOk.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.butOk.Location = new System.Drawing.Point(8, 208);
			this.butOk.Name = "butOk";
			this.butOk.Size = new System.Drawing.Size(328, 23);
			this.butOk.TabIndex = 14;
			this.butOk.Text = "OK";
			this.butOk.Click += new System.EventHandler(this.butOk_Click);
			// 
			// label7
			// 
			this.label7.ContextMenu = this.cmDbEdit;
			this.label7.Location = new System.Drawing.Point(8, 16);
			this.label7.Name = "label7";
			this.label7.TabIndex = 15;
			this.label7.Text = "Active Database";
			this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
			// 
			// cmDbEdit
			// 
			this.cmDbEdit.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					 this.mAddNew,
																					 this.mEdit,
																					 this.mDelete});
			this.cmDbEdit.Popup += new System.EventHandler(this.cmDbEdit_Popup);
			// 
			// mAddNew
			// 
			this.mAddNew.Index = 0;
			this.mAddNew.Text = "Add New";
			this.mAddNew.Click += new System.EventHandler(this.mAddNew_Click);
			// 
			// mDelete
			// 
			this.mDelete.Index = 2;
			this.mDelete.Text = "Delete";
			this.mDelete.Click += new System.EventHandler(this.mDelete_Click);
			// 
			// comboDatabases
			// 
			this.comboDatabases.ContextMenu = this.cmDbEdit;
			this.comboDatabases.DisplayMember = "\"Label\"";
			this.comboDatabases.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
			this.comboDatabases.Location = new System.Drawing.Point(112, 16);
			this.comboDatabases.Name = "comboDatabases";
			this.comboDatabases.Size = new System.Drawing.Size(224, 21);
			this.comboDatabases.TabIndex = 16;
			this.comboDatabases.Text = "";
			this.comboDatabases.SelectedIndexChanged += new System.EventHandler(this.comboDatabases_SelectedIndexChanged);
			// 
			// mEdit
			// 
			this.mEdit.Index = 1;
			this.mEdit.Text = "Edit Name...";
			this.mEdit.Click += new System.EventHandler(this.mEdit_Click);
			// 
			// DbSourceDialog
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(344, 406);
			this.ContextMenu = this.cmDbEdit;
			this.Controls.Add(this.comboDatabases);
			this.Controls.Add(this.label7);
			this.Controls.Add(this.butOk);
			this.Controls.Add(this.rtbLog);
			this.Controls.Add(this.textOption);
			this.Controls.Add(this.textPassword);
			this.Controls.Add(this.textUsername);
			this.Controls.Add(this.textServerName);
			this.Controls.Add(this.textDbName);
			this.Controls.Add(this.textDriver);
			this.Controls.Add(this.label6);
			this.Controls.Add(this.label5);
			this.Controls.Add(this.label4);
			this.Controls.Add(this.label3);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.label1);
			this.Name = "DbSourceDialog";
			this.Text = "Your Databases";
			this.Closing += new System.ComponentModel.CancelEventHandler(this.DbSourceDialog_Closing);
			this.ResumeLayout(false);

		}
		#endregion

		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.Label label5;
		private System.Windows.Forms.Label label6;
		private System.Windows.Forms.TextBox textDriver;
		private System.Windows.Forms.TextBox textDbName;
		private System.Windows.Forms.TextBox textServerName;
		private System.Windows.Forms.TextBox textUsername;
		private System.Windows.Forms.TextBox textPassword;
		private System.Windows.Forms.TextBox textOption;
		private System.Windows.Forms.RichTextBox rtbLog;
		private System.Windows.Forms.Button butOk;
		private System.Windows.Forms.Label label7;
		private System.Windows.Forms.ComboBox comboDatabases;
		private System.Windows.Forms.ContextMenu cmDbEdit;
		private System.Windows.Forms.MenuItem mAddNew;
		private System.Windows.Forms.MenuItem mDelete;
		private System.Windows.Forms.MenuItem mEdit;

		public DbSource DummyDbSource;
		public int ActiveSourceInd
		{
			get
			{
				return comboDatabases.SelectedIndex;
			}
		}

		public int LastActiveIndex=-1;
		public DbSourceDialog(int activeSourceInd)
		{
			InitializeComponent();

			DummyDbSource = new DbSource();

			//	Populates the combo box.
			for(int i=0; i<FormParse.DbSources.Length; i++)
				comboDatabases.Items.Add(FormParse.DbSources[i]);
			
			//	Activates the appropriate index of the combo box.
			if(ActiveSourceInd < FormParse.DbSources.Length)
				comboDatabases.SelectedIndex = activeSourceInd;
			else
				comboDatabases.SelectedIndex = 0;

			LastActiveIndex = activeSourceInd;
			RefreshActiveFields();
			this.DialogResult=DialogResult.Cancel;
		}
		/// <summary>
		/// Refreshes the active fields with the appropriate info from the ActiveSourceInd of FormParse.DbSources.
		/// </summary>
		public void RefreshActiveFields()
		{
			DbSource source = FormParse.DbSources[ActiveSourceInd];
			//	Fill the text fields.
			textDriver.Text = source.Driver;
			textDbName.Text = source.Database;
			textServerName.Text = source.Server;
			textOption.Text = Convert.ToString(source.Option);
			textUsername.Text = source.User;
			textPassword.Text = source.Password;

			//	Fill the rtbLog.
			int i;
			rtbLog.Text = "";
			for(i=0; i<source.ConnectionLog.Count; i++)
				rtbLog.Text = rtbLog.Text + (string)source.ConnectionLog[i] + '\n';
		}
		/// <summary>
		/// Updates the DbSource at the given index with the field values of the form.
		/// </summary>
		/// <param name="index">int  The index of the DbSource within FormParse.DbSources</param>
		public void SaveFieldsToSource(int index)
		{
			DbSource source = FormParse.DbSources[index];

			string oldString = source.ConnectString;
			source.Driver = textDriver.Text;
			source.Database = textDbName.Text;
			source.Server = textServerName.Text;
			try	{	source.Option = Convert.ToInt32(textOption.Text);  }
			catch{}
			source.User = textUsername.Text;
			source.Password = textPassword.Text;

			//	Check to see if there was a change.  If so, then record it in the logs.
			string newString = source.ConnectString;
			if(oldString != newString)
				source.ConnectionLog.Add("Changed connection string from \n" + 
					oldString + "\nto\n" + newString);
		}
		/// <summary>
		/// OK, SaveFieldToSource(ActiveSourceInd) and SerializeBinary().
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void butOk_Click(object sender, System.EventArgs e)
		{
			SaveFieldsToSource(ActiveSourceInd);
			SerializeBinary();
			this.DialogResult=DialogResult.OK;
			this.Close();
		}
		/// <summary>
		/// The method that saves a Databases.DbSource file to the specified directory.
		/// </summary>
		/// <param name="directory">string  The path for saving.</param>
		public void SerializeBinary()
		{
			IFormatter formatter = new BinaryFormatter();
			Stream stream;
			stream = new FileStream(Application.StartupPath + '\\' + DbSource.FileName, FileMode.Create, FileAccess.Write, FileShare.None);
			formatter.Serialize(stream,FormParse.DbSources);
			stream.Close();
		}
		/// <summary>
		/// When the context menu pops up, Delete will only be enabled if FormParse.DbSources has a length
		/// of 2 or greater.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void cmDbEdit_Popup(object sender, System.EventArgs e)
		{
			if(comboDatabases.Items.Count > 1)
				mDelete.Enabled = true;
			else
				mDelete.Enabled = false;
		}
		/// <summary>
		/// SaveFieldsToSource(LastActiveIndex);  LastActiveIndex = ActiveSourceInd;
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void comboDatabases_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if(LastActiveIndex!=-1)
				SaveFieldsToSource(LastActiveIndex);
			LastActiveIndex = ActiveSourceInd;
			RefreshActiveFields();
		}
		/// <summary>
		/// Prompt for saving, allow them to cancel the closing event if necessary.  Yes/No/Cancel option.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void DbSourceDialog_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			if(! (this.DialogResult==DialogResult.OK) )
			{
				DialogResult dr = MessageBox.Show(this, "Save changes?", "Save changes?", MessageBoxButtons.YesNoCancel);
				if(dr == DialogResult.Yes)
				{
					SerializeBinary();
					this.DialogResult = DialogResult.OK;
				}
				else
				{
					e.Cancel = dr==DialogResult.Cancel;	//	maybe cancel the closing event
					this.DialogResult = DialogResult.Cancel;	//	signal that this dialog result is Cancel (in case of close).
				}
			}
		}

		private void mEdit_Click(object sender, System.EventArgs e)
		{
			LabelEditDialog led = new LabelEditDialog("Edit name.", FormParse.DbSources[ActiveSourceInd].Label);
			if(led.ShowDialog()==DialogResult.OK)
			{
				FormParse.DbSources[ActiveSourceInd].Label=led.Label;
				comboDatabases.Items[ActiveSourceInd] = DummyDbSource;
				comboDatabases.Items[ActiveSourceInd] = FormParse.DbSources[ActiveSourceInd];
			}
		}

		private void mAddNew_Click(object sender, System.EventArgs e)
		{
			SaveFieldsToSource(ActiveSourceInd);
			DbSource[] old = FormParse.DbSources;
			FormParse.DbSources = new DbSource[old.Length+1];
			for(int i=0; i<old.Length; i++)
				FormParse.DbSources[i] = old[i];
			FormParse.DbSources[old.Length] = new DbSource();

			comboDatabases.Items.Add(FormParse.DbSources[old.Length]);
			FormParse.DbSources[old.Length].Label = "New Database";
			comboDatabases.SelectedIndex = old.Length;
			comboDatabases.Refresh();
            RefreshActiveFields();
			mEdit_Click(sender, e);
		}

		private void mDelete_Click(object sender, System.EventArgs e)
		{
			int remove = ActiveSourceInd;

			DbSource[] old = FormParse.DbSources;
			FormParse.DbSources = new DbSource[old.Length-1];
			int ct=0;
			for(int i=0; i<old.Length; i++)
				if(i != remove)
					FormParse.DbSources[ct++] = old[i];
			comboDatabases.Items.RemoveAt(remove);
			comboDatabases.SelectedIndex = 0;
			LastActiveIndex = -1;
			RefreshActiveFields();
		}
	}
}
